package com.example.dockerdemo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.dockerdemo.entity.MyEntity;
import com.example.dockerdemo.mapper.IMyEntityMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.types.RedisClientInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class HelloController {

    public static final String REDIS_KEY = "docker:index";

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisConnectionFactory redisConnectionFactory;

    @Autowired
    IMyEntityMapper iMyEntityMapper;

    private void printRedis() {
        RedisConnection connection = redisConnectionFactory.getConnection();
        List<RedisClientInfo> clientList = connection.getClientList();
        for (RedisClientInfo redisClientInfo : clientList) {
            logger.info("redisClientInfo.getName()" + redisClientInfo.getName());
            logger.info("redisClientInfo.getAddressPort()" + redisClientInfo.getAddressPort());
        }
    }

    private final Logger logger = LoggerFactory.getLogger(HelloController.class);

    @GetMapping("/hello")
    public String hello() {
        logger.info("hello......");
        return "hello";
    }

    @GetMapping("/redis")
    public String redis(Model model) {
        printRedis();
        logger.info("redis......");
        model.addAttribute("message", addIndex());
        return "redis";
    }

    @GetMapping("/mysql/select/{id}")
    @ResponseBody
    public String query(@PathVariable Long id) {
        logger.info("select id={}", id);
        MyEntity myEntity = iMyEntityMapper.selectById(id);
        return JSONObject.toJSONString(myEntity);
    }

    @GetMapping("/mysql/insert")
    @ResponseBody
    public int insert() {
        MyEntity myEntity = new MyEntity("c1" + Math.random(), "c2" + Math.random());
        int insert = iMyEntityMapper.insert(myEntity);
        logger.info("insert count={}", insert);
        return insert;
    }

    private synchronized Long addIndex() {
        String s = stringRedisTemplate.opsForValue().get(REDIS_KEY);
        if (s == null || "".equals(s)) {
            stringRedisTemplate.opsForValue().set(REDIS_KEY, "0");
            return 0L;
        }
        Long val = Long.parseLong(s) + 1;
        stringRedisTemplate.opsForValue().set(REDIS_KEY, val.toString());
        return val;
    }

}
